<template>
  <div class="goods-region-container">
    <!-- 标题和筛选区域 -->
    <div class="header">
      <h1>商品区域可视化分析</h1>
      <div class="filters">
        <el-select v-model="selectedRegion" placeholder="选择区域" clearable @change="filterData">
          <el-option
              v-for="region in regions"
              :key="region.id"
              :label="region.name"
              :value="region.id"
          />
        </el-select>
        <el-select v-model="selectedCategory" placeholder="选择分类" clearable @change="filterData">
          <el-option
              v-for="category in categories"
              :key="category.id"
              :label="category.name"
              :value="category.id"
          />
        </el-select>
        <el-button type="primary" @click="refreshData">
          <i class="el-icon-refresh"></i> 刷新数据
        </el-button>
      </div>
    </div>

    <!-- 主内容区 -->
    <div class="dashboard">
      <!-- 左侧图表 -->
      <div class="left-panel">
        <el-card class="card">
          <template #header>
            <div class="card-header">
              <span>区域门店分布</span>
              <div class="card-tool">
                <el-tag type="success">门店数量统计</el-tag>
              </div>
            </div>
          </template>
          <div class="chart-container">
            <div ref="regionChart" style="height: 350px;"></div>
          </div>
        </el-card>

        <el-card class="card">
          <template #header>
            <div class="card-header">
              <span>商品分类结构</span>
              <div class="card-tool">
                <el-tag type="info">商品数量占比</el-tag>
              </div>
            </div>
          </template>
          <div class="chart-container">
            <div ref="categoryChart" style="height: 300px;"></div>
          </div>
        </el-card>
      </div>

      <!-- 右侧数据图表 -->
      <div class="right-panel">
        <el-card class="card">
          <template #header>
            <div class="card-header">
              <span>区域商品统计</span>
              <div class="card-tool">
                <el-tag type="warning">多维度分析</el-tag>
              </div>
            </div>
          </template>
          <div class="chart-container">
            <div ref="regionStats" style="height: 300px;"></div>
          </div>
        </el-card>

        <el-card class="card">
          <template #header>
            <div class="card-header">
              <span>门店商品关系</span>
              <div class="card-tool">
                <el-tag type="danger">关系网络</el-tag>
              </div>
            </div>
          </template>
          <div class="chart-container">
            <div ref="storeGoodsChart" style="height: 350px;"></div>
          </div>
        </el-card>
      </div>
    </div>

    <!-- 底部卡片 -->
    <div class="bottom-panel">
      <el-card class="card">
        <template #header>
          <div class="card-header">
            <span>商品区域综合分析</span>
            <div class="card-tool">
              <el-tag type="primary">综合数据视图</el-tag>
            </div>
          </div>
        </template>
        <div class="chart-container">
          <div ref="comprehensiveChart" style="height: 400px;"></div>
        </div>
      </el-card>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue';
import * as echarts from 'echarts';
import { get } from '@/plugins/axios';

// 图表引用
const regionChart = ref(null);
const categoryChart = ref(null);
const regionStats = ref(null);
const storeGoodsChart = ref(null);
const comprehensiveChart = ref(null);

// 数据
const allRegions = ref([]);
const allStores = ref([]);
const allGoods = ref([]);
const allCategories = ref([]);

const regions = ref([]);
const stores = ref([]);
const goods = ref([]);
const categories = ref([]);
const selectedRegion = ref(null);
const selectedCategory = ref(null);

// 初始化图表
function initCharts() {
  initRegionChart();
  initCategoryChart();
  initRegionStats();
  initStoreGoodsChart();
  initComprehensiveChart();
}

// 区域门店分布 - 柱状图
function initRegionChart() {
  if (!regionChart.value) return;
  const chart = echarts.init(regionChart.value);

  // 添加数据检查
  if (!regions.value.length || !stores.value.length) {
    chart.setOption({
      title: {
        text: '暂无数据',
        left: 'center',
        top: 'center'
      }
    });
    return;
  }

  // 按区域统计门店数量
  const regionData = regions.value.map(region => {
    const storesInRegion = stores.value.filter(store =>
        store.regionId === region.id
    );
    return {
      name: region.name,
      value: storesInRegion.length,
      address: region.address
    };
  });
  const option = {
    tooltip: {
      trigger: 'axis',
      formatter: function(params) {
        const data = params[0].data;
        return `
          <b>${data.name}</b><br/>
          门店数量: ${data.value}家<br/>
          区域地址: ${data.address || '未设置'}
        `;
      }
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '10%',
      top: '5%',
      containLabel: true
    },
    xAxis: {
      type: 'category',
      data: regionData.map(d => d.name),
      axisLabel: {
        interval: 0,
        rotate: 30
      }
    },
    yAxis: {
      type: 'value',
      name: '门店数量',
      axisLine: {
        show: true
      }
    },
    series: [
      {
        name: '门店数量',
        type: 'bar',
        data: regionData,
        itemStyle: {
          color: function(params) {
            // 根据门店数量设置不同颜色
            const colors = ['#36cfc9', '#13c2c2', '#08979c', '#006d75', '#00474f'];
            const index = Math.min(Math.floor(params.data.value / 5), 4);
            return colors[index];
          }
        },
        label: {
          show: true,
          position: 'top',
          formatter: '{c}家'
        },
        barWidth: '60%'
      }
    ]
  };

  chart.setOption(option);
  window.addEventListener('resize', () => chart.resize());
}

// 商品分类结构 - 饼图
function initCategoryChart() {
  if (!categoryChart.value) return;
  const chart = echarts.init(categoryChart.value);

  // 获取一级分类
  const topCategories = categories.value.filter(cat => cat.level === 1);

  // 统计每个一级分类的商品数量
  const categoryData = topCategories.map(category => {
    const goodsCount = goods.value.filter(g =>
        g.categoryId === category.id
    ).length;

    return {
      name: category.name,
      value: goodsCount
    };
  });

  // 过滤掉商品数量为0的分类
  const filteredData = categoryData.filter(item => item.value > 0);

  const option = {
    tooltip: {
      trigger: 'item',
      formatter: '{b}: {c} ({d}%)'
    },
    legend: {
      type: 'scroll',
      orient: 'vertical',
      right: 10,
      top: 20,
      bottom: 20,
    },
    series: [
      {
        name: '商品分类',
        type: 'pie',
        radius: ['40%', '70%'],
        center: ['40%', '50%'],
        avoidLabelOverlap: false,
        itemStyle: {
          borderRadius: 10,
          borderColor: '#fff',
          borderWidth: 2
        },
        label: {
          show: false,
          position: 'center'
        },
        emphasis: {
          label: {
            show: true,
            fontSize: '18',
            fontWeight: 'bold'
          }
        },
        labelLine: {
          show: false
        },
        data: filteredData
      }
    ]
  };

  chart.setOption(option);
  window.addEventListener('resize', () => chart.resize());
}

// 区域商品统计
function initRegionStats() {
  if (!regionStats.value) return;
  const chart = echarts.init(regionStats.value);


  // 按区域统计商品
  const regionData = regions.value.map(region => {
    const storesInRegion = stores.value.filter(store =>
        store.regionId === region.id,
    );
    const storeIds = storesInRegion.map(s => s.id);
    const goodsInRegion = goods.value.filter(good =>
        storeIds.includes(good.categoryId)
    );

    return {
      name: region.name,
      goodsCount: goodsInRegion.length,
      avgPrice: goodsInRegion.reduce((sum, g) => sum + (g.price || 0), 0) / (goodsInRegion.length || 1) || 0,
      totalSales: goodsInRegion.reduce((sum, g) => sum + (g.sales || 0), 0)
    };
  });

  // if (!regionStats.value) return;
  // const chart = echarts.init(regionStats.value);
  //
  // // 按分类统计商品
  // const regionData = regions.value
  //     .filter(cat => cat.level === 1)
  //     .map(category => {
  //       const goodsInCategory = goods.value.filter(good =>
  //           good.categoryId === category.id
  //       );
  //
  //       return {
  //         name: regions.name,
  //         goodsCount: goodsInCategory.length,
  //         avgPrice: goodsInCategory.reduce((sum, g) => sum + (g.price || 0), 0) / (goodsInCategory.length || 1) || 0,
  //         totalSales: goodsInCategory.reduce((sum, g) => sum + (g.sales || 0), 0)
  //       };
  //     });


  const option = {
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'shadow'
      }
    },
    legend: {
      data: ['商品数量', '平均价格', '总销量'],
      bottom: 10
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '15%',
      containLabel: true
    },
    xAxis: {
      type: 'category',
      data: regionData.map(d => d.name),
      axisLabel: {
        interval: 0,
        rotate: 30
      }
    },
    yAxis: [
      {
        type: 'value',
        name: '商品数量',
        position: 'left'
      },
      {
        type: 'value',
        name: '平均价格',
        position: 'right',
        axisLine: {
          show: true,
          lineStyle: {
            color: '#ff9c6e'
          }
        },
        axisLabel: {
          formatter: '¥{value}'
        }
      }
    ],
    series: [
      {
        name: '商品数量',
        type: 'bar',
        data: regionData.map(d => d.goodsCount),
        itemStyle: {
          color: '#36cfc9'
        }
      },
      {
        name: '平均价格',
        type: 'line',
        yAxisIndex: 1,
        data: regionData.map(d => d.avgPrice.toFixed(2)),
        itemStyle: {
          color: '#ff9c6e'
        }
      },
      {
        name: '总销量',
        type: 'bar',
        data: regionData.map(d => d.totalSales),
        itemStyle: {
          color: '#597ef7'
        }
      }
    ]
  };

  chart.setOption(option);
  window.addEventListener('resize', () => chart.resize());
}

// 门店商品关系图
function initStoreGoodsChart() {
  if (!storeGoodsChart.value) return;
  const chart = echarts.init(storeGoodsChart.value);

  // 构建门店-商品关系数据
  const nodes = [
    ...regions.value.map(region => ({
      id: `region_${region.id}`,
      name: region.name,
      symbolSize: 40,
      itemStyle: { color: '#36cfc9' },
      category: 0
    })),
    ...stores.value.map(store => ({
      id: `store_${store.id}`,
      name: store.name,
      symbolSize: 30,
      itemStyle: { color: '#597ef7' },
      category: 1
    })),
    ...goods.value.slice(0, 50).map(good => ({ // 限制商品数量
      id: `good_${good.id}`,
      name: good.name,
      symbolSize: 20,
      itemStyle: { color: '#ff9c6e' },
      category: 2
    }))
  ];

  const links = [
    // 区域-门店关系
    ...stores.value.map(store => ({
      source: `region_${store.regionId}`,
      target: `store_${store.id}`
    })),
    // 门店-商品关系（简化）
    ...goods.value.slice(0, 50).map(good => ({
      source: `store_${good.categoryId}`,
      target: `good_${good.id}`
    }))
  ];

  const option = {
    tooltip: {
      formatter: function(params) {
        if (params.dataType === 'node') {
          return params.data.name;
        }
      }
    },
    legend: {
      data: ['区域', '门店', '商品'],
      bottom: 0
    },
    series: [
      {
        name: '商品区域关系',
        type: 'graph',
        layout: 'force',
        force: {
          repulsion: 300,
          edgeLength: 100
        },
        roam: true,
        label: {
          show: true,
          position: 'right'
        },
        data: nodes,
        links: links,
        categories: [
          { name: '区域' },
          { name: '门店' },
          { name: '商品' }
        ],
        lineStyle: {
          color: 'source',
          curveness: 0.3
        },
        emphasis: {
          focus: 'adjacency',
          lineStyle: {
            width: 5
          }
        }
      }
    ]
  };

  chart.setOption(option);
  window.addEventListener('resize', () => chart.resize());
}

// 综合分析图表
function initComprehensiveChart() {
  if (!comprehensiveChart.value) return;
  const chart = echarts.init(comprehensiveChart.value);

  // 按分类统计商品
  const categoryStats = categories.value
      .filter(cat => cat.level === 1)
      .map(category => {
        const goodsInCategory = goods.value.filter(good =>
            good.categoryId === category.id
        );

        return {
          name: category.name,
          goodsCount: goodsInCategory.length,
          avgPrice: goodsInCategory.reduce((sum, g) => sum + (g.price || 0), 0) / (goodsInCategory.length || 1) || 0,
          totalSales: goodsInCategory.reduce((sum, g) => sum + (g.sales || 0), 0)
        };
      });

  const option = {
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'cross',
        crossStyle: {
          color: '#999'
        }
      }
    },
    toolbox: {
      feature: {
        dataView: { show: true, readOnly: false },
        magicType: { show: true, type: ['line', 'bar'] },
        restore: { show: true },
        saveAsImage: { show: true }
      }
    },
    legend: {
      data: ['商品数量', '平均价格', '总销量'],
      bottom: 10
    },
    xAxis: [
      {
        type: 'category',
        data: categoryStats.map(d => d.name),
        axisPointer: {
          type: 'shadow'
        },
        axisLabel: {
          interval: 0,
          rotate: 30
        }
      }
    ],
    yAxis: [
      {
        type: 'value',
        name: '商品数量',
        min: 0,
        axisLabel: {
          formatter: '{value} 件'
        }
      },
      {
        type: 'value',
        name: '平均价格',
        min: 0,
        axisLabel: {
          formatter: '¥{value}'
        }
      }
    ],
    series: [
      {
        name: '商品数量',
        type: 'bar',
        data: categoryStats.map(d => d.goodsCount),
        itemStyle: {
          color: '#36cfc9'
        }
      },
      {
        name: '平均价格',
        type: 'line',
        yAxisIndex: 1,
        data: categoryStats.map(d => d.avgPrice.toFixed(2)),
        itemStyle: {
          color: '#ff9c6e'
        }
      },
      {
        name: '总销量',
        type: 'bar',
        data: categoryStats.map(d => d.totalSales),
        itemStyle: {
          color: '#597ef7'
        }
      }
    ]
  };

  chart.setOption(option);
  window.addEventListener('resize', () => chart.resize());
}

// 加载数据
async function loadData() {
  try {
    // 使用 Promise.all 确保所有数据加载完成
    const [regionsData, storesData, goodsData, categoriesData, regionStoresData,cateStoresData] = await Promise.all([
      new Promise((resolve) => {
        get('/region/list', {}, content => resolve(content || []));
      }),
      new Promise((resolve) => {
        get('/stores/list', {PageNo: 1, PageSize: 100}, content =>
            resolve(content?.records || [])
        );
      }),
      new Promise((resolve) => {
        get('/goods/getList', {}, content => resolve(content || []));
      }),
      new Promise((resolve) => {
        get('/category/list', {}, content => resolve(content || []));
      }),
      // +++ 新增：加载区域门店关联数据 +++
      new Promise((resolve) => {
        get('/regionStores/list', {}, content => resolve(content || []));
      }),
      new Promise((resolve) => {
        get('/cateStores/list', {}, content => resolve(content || []));
      })
    ]);

    // 保存原始数据
    allRegions.value = regionsData;
    allStores.value = storesData;
    allGoods.value = goodsData;
    allCategories.value = categoriesData;
    const allRegionStores = regionStoresData;
    const allCateStores = cateStoresData;

    // +++ 创建门店ID到区域ID的映射 +++
    const storeRegionMap = {};
    allRegionStores.forEach(rs => {
      storeRegionMap[rs.storesId] = rs.regionId;
    });


    // +++ 为门店添加区域ID属性 +++
    allStores.value.forEach(store => {
      store.regionId = storeRegionMap[store.id] || null;
    });

    // // +++ 为商品添加门店ID和区域ID +++
    // allGoods.value.forEach(good => {
    //   // 添加门店ID（如果商品已有storeId则保留）
    //   if (!good.storeId) {
    //     good.storeId =categoriesData[good.categoryID] || null; // 使用storesId作为后备
    //   }
    //
    //   // 添加区域ID
    //   const store = allStores.value.find(s => s.id === good.storeId);
    //   good.regionId = store ? store.regionId : null;
    // });


    // 初始加载时显示所有数据
    regions.value = [...allRegions.value];
    stores.value = [...allStores.value];
    goods.value = [...allGoods.value];
    categories.value = [...allCategories.value];


    // 初始化图表
    initCharts();
  } catch (error) {
    console.error('加载数据失败:', error);
  }
}

// 筛选数据
function filterData() {
  // 区域筛选
  if (selectedRegion.value) {
    regions.value = allRegions.value.filter(r => r.id === selectedRegion.value);
    stores.value = allStores.value.filter(s => s.regionId === selectedRegion.value);
  } else {
    regions.value = [...allRegions.value];
    stores.value = [...allStores.value];
  }

  // 分类筛选
  if (selectedCategory.value) {
    // 获取所有子分类ID
    const getAllSubCategoryIds = (categoryId) => {
      const subIds = [categoryId];
      const findSub = (parentId) => {
        const subs = allCategories.value.filter(c => c.parentId === parentId);
        subs.forEach(sub => {
          subIds.push(sub.id);
          findSub(sub.id);
        });
      };
      findSub(categoryId);
      return subIds;
    };

    const categoryIds = getAllSubCategoryIds(selectedCategory.value);
    categories.value = allCategories.value.filter(c => categoryIds.includes(c.id));
    goods.value = allGoods.value.filter(g => categoryIds.includes(g.categoryId));
  } else {
    categories.value = [...allCategories.value];
    goods.value = [...allGoods.value];
  }

  // 重新渲染图表
  initCharts();
}

// 刷新数据
function refreshData() {
  selectedRegion.value = null;
  selectedCategory.value = null;
  loadData();
}

// 组件挂载时加载数据
onMounted(() => {
  loadData();
});
</script>

<style scoped>
.goods-region-container {
  padding: 20px;
  background: linear-gradient(135deg, #f5f7fa 0%, #e4eff9 100%);
  min-height: 100vh;
}

.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  padding: 15px 25px;
  background: white;
  border-radius: 12px;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.08);
  border-left: 5px solid #36cfc9;
}

.header h1 {
  margin: 0;
  font-size: 24px;
  color: #1c7ed6;
  font-weight: 600;
  letter-spacing: 0.5px;
}

.filters {
  display: flex;
  gap: 15px;
  align-items: center;
}

.dashboard {
  display: flex;
  gap: 20px;
  margin-bottom: 20px;
}

.left-panel, .right-panel {
  flex: 1;
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.card {
  border-radius: 12px;
  box-shadow: 0 6px 16px rgba(0, 0, 0, 0.08);
  transition: all 0.4s ease;
  overflow: hidden;
  background: white;
  border: none;
}

.card:hover {
  box-shadow: 0 10px 25px rgba(0, 0, 0, 0.15);
  transform: translateY(-5px);
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 16px 24px;
  background: linear-gradient(90deg, #f0f9ff, #e6f7ff);
  border-bottom: 1px solid #e8f4ff;
}

.card-header span {
  font-size: 18px;
  font-weight: 600;
  color: #1c7ed6;
}

.card-tool {
  display: flex;
  gap: 10px;
}

.chart-container {
  padding: 15px;
  height: 100%;
  background: #fafdff;
}

.bottom-panel {
  margin-top: 20px;
}

.el-select {
  width: 200px;
}

.el-button {
  padding: 10px 20px;
  border-radius: 8px;
  font-weight: 500;
}

@media (max-width: 1200px) {
  .dashboard {
    flex-direction: column;
  }

  .filters {
    flex-wrap: wrap;
  }

  .header {
    flex-direction: column;
    gap: 15px;
    align-items: flex-start;
  }
}

@media (max-width: 768px) {
  .filters {
    width: 100%;
    flex-direction: column;
  }

  .el-select {
    width: 100%;
  }
}
</style>